import * as path from "path";
import * as express from "express";
import * as bodyParser from "body-parser";
import * as cookieParser from "cookie-parser";
import * as _ from "lodash";
import * as swig from "swig";

// 移除了 ysHelper 插件的导入

const app = express();

let is_server = Boolean(process.env.YsServer);
let gc: CStatic = {
  debug: process.env.NODE_ENV == "dev",
  root: path.join(__dirname, "..", ".."),
  baseUrl: process.env.baseUrl || "",
  redirectUrl: process.env.redirectUrl || "",
  port: Number(process.env.port!) || 8080,
  projectName: process.env.projectName || "nodejs-web-corp-instructorAgent",
};
let gm: MStatic2 = {
  errors: {},
  _: _,
};

global.C = gc;
global.M = gm;

if (!is_server) {
  app.use("/static", express.static(path.join(C.root, "static")));
}

app.locals = {
  baseUrl: C.baseUrl,
};

app.enable("trust proxy");
app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
app.use(cookieParser());

// 替换 ysHelper.tools.remoteConfig(["api_qy"])
Promise.resolve().then(() => {
  const config = {
    // 这里添加您原本从 remoteConfig 获取的配置
    // 例如:
    // api_qy: {
    //   url: process.env.API_QY_URL || "",
    //   appId: process.env.API_QY_APPID || "",
    //   secret: process.env.API_QY_SECRET || ""
    // }
  };
  C = M._.assign(C, config);
  if (!is_server) {
    swig.setDefaults({
      cache: false,
    });
  }

  app.set("views", path.join(C.root, "backend", "views"));
  app.engine("html", swig.renderFile);
  app.engine("swig", swig.renderFile);
  app.set("view engine", "swig");

  // 移除了 NSQ 相关的代码，使用控制台记录请求
  app.use((req, res, next) => {
    console.log('第一个中间件');
    console.log(
      `${new Date().toISOString()} - ${req.method} ${req.url} - IP: ${req.ip}`
    );
    next();
  });

  // 替换 ysHelper.expressMiddleWares.getCorpInfo
  app.use((req, res, next) => {
    console.log('第二个中间件');
    // 这里实现您自己的企业信息获取逻辑
    // req.companyId = ...
    next();
  });
  // 移除了 vui 相关的中间件
  
  // 如果需要替代功能，可以添加自定义中间件
  app.use((req, res, next) => {
    console.log('第三个中间件');
    // 可以在这里添加自定义的企业头部处理逻辑
    next();
  });
  
  app.use((req, res, next) => {
    // 可以在这里添加自定义的通知处理逻辑
    next();
  });
  
  const router = require("./routes/router");
  router.set(app);
  // corpInfoMiddleware.after(app)

  app.use((req, res) => {
    if (req.xhr) {
      res.status(404).json({
        status: false,
      });
    } else {
      res.status(404).render("404");
    }
  });

  // 替换 ysHelper.expressMiddleWares.errorNext(opts, ajax_opts)
  app.use((err: any, req: any, res: any, next: any) => {
    console.error(err.stack);
    if (req.xhr) {
      res.status(500).json({
        status: false,
        message: err.message || "Internal Server Error"
      });
    } else {
      res.status(500).render("error", { error: err });
    }
  });

  let s = app.listen(C.port, () => {
    const { address, port } = s.address() as any;
    console.log("listen at http://%s:%s", address, port);
  });
});